<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
      #canvas {
          background: #f1f1f1;
      }
  </style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
    window.onload = () => {
        const canvas = document.getElementById('canvas')
        const ctx = canvas.getContext('2d')
        const img = new Image()
        img.crossOrigin = 'anonymous'
        img.src = 'https://mdn.github.io/dom-examples/canvas/pixel-manipulation/assets/rhino.jpg'
        img.onload = ()=>{
            ctx.drawImage(img,0,0,500,500)
            // canvas.toDataURL(type, encoderOptions); type 可选 图片格式，
            // 默认为 image/png 在指定图片格式为 image/jpeg 或 image/webp的情况下，可以从 0 到 1 的区间内选择图片的质量。如果超出取值范围，将会使用默认值 0.92。其他参数会被忽略。

            // const dataURL = canvas.toDataURL();
            const dataURL = canvas.toDataURL("image/jpeg", 1.0);
            // const dataURL = canvas.toDataURL("image/jpeg", 0.1);
            const newImg = new Image()
            newImg.src = dataURL
            newImg.onload = ()=>{
                canvas.parentNode.insertBefore(newImg,canvas)
            }
        }

    }

</script>
</body>
</html>
